package com.maizhi.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.maizhi.model.Files;

public class uploadUtil {
	
	Logger logger = Logger.getLogger(uploadUtil.class); 
	public static ResourceBundle config ;
	
	private String SavePath;
	private String SaveBAKPath;
	//设置上传文件最大值
	private long MAX_SIZE = 300 * 1024 * 1024;
	//默认的文件上传类型限制
    private String allowFileTypes;
	
	public uploadUtil(){
		config = ResourceBundle.getBundle("config");
		allowFileTypes= config.getString("allowFileTypes");
		SavePath = config.getString("SavePath");
		SaveBAKPath = config.getString("SaveBAKPath");
	}
	
	public long getMAX_SIZE() {
		return MAX_SIZE;
	}

	public void setMAX_SIZE(long max_size) {
		MAX_SIZE = max_size;
	}
    
    private boolean isAllowFileType(String fileType)
    {
        if (allowFileTypes.length() > 0 && fileType.trim().length() > 0)
            return allowFileTypes.indexOf(fileType.toLowerCase()) != -1;
        else
            return true;
    }

    /**
     * @return [String] 允许上传的文件类型
     */
    public String getAllowFileTypes()
    {
        return allowFileTypes;
    }

    /**
     * 设置允许上传的文件类型，默认是""，无限制
     * 
     * @param allowFileTypes
     */
    public void setAllowFileTypes(String allowFileTypes)
    {
        this.allowFileTypes = allowFileTypes;
    }

    public void addAllowFileTypes(String allowFileTypes)
    {
        this.allowFileTypes += ("," + allowFileTypes);
    }
	
    //下载
    public void downLoad(String filename,String oldFileName,HttpServletResponse response,boolean isOnLine) throws Exception
	{
    	String filePath = filename;
		
		File f = new File(filePath);
		
		if(!f.exists())
		{
			response.sendError(404,"File not found, fileName:"+filePath);
			return;
		}
		
		BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
		byte[] buf = new byte[1024];
		int len = 0;
		
		//String fileName = f.getName();
		String fileName = new String(oldFileName.getBytes("GBK"),"ISO8859_1");       
		
		
		response.reset(); //非常重要
		if(isOnLine)//在线打开方式
		{ 
			URL u = new URL("file:///"+filePath);
			response.setContentType("application/zip");
			if (u.openConnection().getContentType().equals("text/plain") ||
				u.openConnection().getContentType().equals("text/xml") ||
				u.openConnection().getContentType().equals("text/html"))
			{
				response.setContentType(u.openConnection().getContentType()+";charset=GB2312");
			}else response.setContentType(u.openConnection().getContentType()+";charset=UTF-8");
			//text/html
			 
			response.setHeader("Content-Disposition", "inline; filename="+fileName);
			//文件名应该编码成UTF-8
		}else
		{ 	//纯下载方式
			response.setContentType("application/x-msdownload"); 
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName); 
		}	
		
		OutputStream out = response.getOutputStream();
		while((len = br.read(buf)) >0)
		out.write(buf,0,len);
		br.close();
		out.close();
	} 
    
    
    //上传
	public List<Files> upload(HttpServletRequest request,HttpServletResponse reponse){
		
		reponse.setContentType("text/html");
		
		// 设置字符编码为UTF-8, 统一编码，处理出现乱码问题
		reponse.setCharacterEncoding("gbk");
		
		List<Files> fileList = new ArrayList();
		try{
			//1. 创建工厂类
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//临时缓存文件路径
			factory.setRepository(new File(this.SaveBAKPath));
			//2. 创建FileUpload对象
			ServletFileUpload upload = new ServletFileUpload(factory);
			//3. 判断是否是上传表单
			
			boolean b = upload.isMultipartContent(request);
			logger.info("判断是否是上传表单 "+b);
			if(!b) {
			    // 不是文件上传
				request.setAttribute("message", "对不起，不是文件上传表单！");
				request.getRequestDispatcher("/message.jsp").forward(request, reponse);
			    return null;
			}
			//是文件上传表单
			//4. 解析request，获得FileItem项
			List<FileItem> fileitems = upload.parseRequest(request);
			
			logger.info("fileitems : "+fileitems);
			
			// 5. 遍历集合
			for(FileItem item : fileitems) {
			    // 判断是不是普通字段
			if(item.isFormField()) {
			    String name = item.getFieldName();
			    String value = item.getString();
			    // 手工的转换了
			    value = new String(value.getBytes("iso-8859-1"),"utf-8");
			    logger.info("导入控件值:"+name+" : "+value);
			} else {
			    // 文件上传字段
			    // 获得文件名
			    String filename = item.getName();
			    logger.info("文件名路径："+filename);
			    filename = filename.substring(filename.lastIndexOf("\\")+1);
			    String fileExt = filename.substring(filename.lastIndexOf(".") + 1);
			   
			    logger.info("文件名："+filename);
			    // 创建文件
			    //ServletContext context = getServletContext();
			    //String dir = context.getRealPath("WEN-INF/upload");
			    //ServletContext servletContext = webApplicationContext.getServletContext();   
		        //String dirPath = servletContext.getRealPath("/WEB-INF/upload/");
			    File file = new File(this.SavePath, filename);
			    file.createNewFile();
			   
			    // 获得流，读取数据写入文件
			    InputStream in = item.getInputStream();
			    FileOutputStream fos = new FileOutputStream(file);
			   
			    int len;
			    byte[] buffer = new byte[1024];
			    while((len=in.read(buffer))>0)
			       fos.write(buffer,0,len);
			    
			    Files files = new Files();
				 
				files.setCreateDate(new Date());
				files.setFileName(filename);
				files.setFilePath(this.SavePath);
				files.setFileSubffix(fileExt);
				files.setFileStatus(1);
				files.setFileSize(item.getSize()); 
				 
				fileList.add(files); 
				 
			    fos.close();
			    in.close();
			    item.delete();    // 删除临时文件
				}
			}
		}catch(Exception e){
			request.setAttribute("message", e.getMessage());
			try {
				request.getRequestDispatcher("/message.jsp").forward(request, reponse);
			} catch (ServletException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return null;
		}
		return fileList;
	}
}
